package com.woniuxy.springsecurity.service.impl;

import com.woniuxy.springsecurity.entity.LoginUserDetails;
import com.woniuxy.springsecurity.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author author
 * @Create 2023-10-26 15:43
 */
@Service
public class LoginUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=null;
        List<String> permissions=new ArrayList<>();
        //从数据库根据用户名查询用户信息
        if("a".equals(username)){
          user=new User(1,"a","$2a$10$CEhZfCMH2KzVVT0Ex6UoDeDLyZ51WevCXKshr3X63kOzrjCYW70d2");
            permissions.add("test");
            permissions.add("add");
        }else if("b".equals(username)){
            user=new User(2,"b","$2a$10$SXKszBA016Vpc97fbWh5L.1MrEHF0k5jd5qyrbWkc1feuDSeGrNk6");
            permissions.add("test");
        }else{
            throw new RuntimeException("用户名不存在");
        }
        //UserDetails存入redis中
        UserDetails userDetails=new LoginUserDetails(user,permissions);
        redisTemplate.opsForValue().set("user:"+username, userDetails);
        return userDetails;
    }
}
